package com.zhiqingchun.web.user;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhiqingchun.dao.article.ArticleResult;
import com.zhiqingchun.dao.article.IArticleDao;
import com.zhiqingchun.dao.category.CategoryResult;
import com.zhiqingchun.dao.category.ICategoryDao;
import com.zhiqingchun.pojo.ArticleDO;
import com.zhiqingchun.pojo.CategoryDO;
import com.zhiqingchun.pojo.Usr;

@Controller
@RequestMapping("/userNewArticle.html")
public class UserNewArticleController {

	@RequestMapping(method = RequestMethod.GET)
	public String userNewArticle(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		
		CategoryDO categoryDO = new CategoryDO();
		categoryDO.setId(0);
		CategoryResult categoryResult = categoryDao.list(categoryDO, null);
		if(categoryResult.isSuccess()) {
			List<CategoryDO> categoryList = categoryResult.getCategoryList();
			map.addAttribute("categoryList", categoryList);
		}
		return "user/userNewArticle";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String userNewArticle2(ModelMap map, HttpServletRequest request, 
			HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8") ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		ArticleDO articleDO  = new ArticleDO();
		articleDO.setCategory(Integer.parseInt(request.getParameter("category")));
		articleDO.setTitle(request.getParameter("title"));
		articleDO.setContent(request.getParameter("content"));
		Usr usr = (Usr) request.getSession().getAttribute("user");
		if (usr != null) {
			articleDO.setAuthor(usr.getId());
		}
		articleDO.setInsertTime(new Date());
		ArticleResult articleResult = articleDao.add(articleDO);
		if (articleResult.isSuccess()) {
			return "redirect:user.html?id=" + usr.getId();
		}
		
		
		return "user/userNewArticle";
	}
	
	@Autowired
	private IArticleDao articleDao;
	
	@Autowired
	private ICategoryDao categoryDao;

	public ICategoryDao getCategoryDao() {
		return categoryDao;
	}

	public void setCategoryDao(ICategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

	public IArticleDao getArticleDao() {
		return articleDao;
	}

	public void setArticleDao(IArticleDao articleDao) {
		this.articleDao = articleDao;
	}
}
